package xyz.qiquqiu.lc4blogdemo.config;

import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.store.memory.chat.InMemoryChatMemoryStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class CommonConfig {

    /**
     * 聊天记忆组件
     * 默认有两个子实现，一个是基于MessageWindow，类似SpringAI
     * 一个基于TokenWindow，作用类似
     */
//    @Bean
    public ChatMemory chatMemory() {
        log.debug("聊天记忆：ChatMemory 初始化...");
        return MessageWindowChatMemory.builder()
                .maxMessages(20)
                .build();
    }

    /**
     * 实现“会话隔离”功能，必备的组件：ChatMemoryProvider
     * 使用provider来提供根据“memoryId” 来get ChatMemory（某个会话记忆）实例的方法
     * 从而实现不同会话的记忆隔离（需要AiService层配合做参数）
     */
    @Bean
    public ChatMemoryProvider chatMemoryProvider() {
        log.debug("聊天记忆提供者：ChatMemoryProvider 初始化...");
        return new ChatMemoryProvider() {
            @Override
            public ChatMemory get(Object memoryId) {
                return MessageWindowChatMemory.builder()
                        .id(memoryId)
                        .maxMessages(20)
                        .chatMemoryStore(new InMemoryChatMemoryStore())
                        .build();
            }
        };
    }
}
